import React, { useState, useEffect, useMemo } from "react";
import { Row, Col, Menu } from "antd";
import Router from "next/router";
import Link from "next/link";
import axios from "axios";
import servicePath from "../config/apiUrl";
import { HomeOutlined, YoutubeOutlined, SmileOutlined, MessageOutlined } from '@ant-design/icons';

const Header = () => {
    // 头部导航
    const [navArray, setNavArray] = useState([]);
    const [current, setCurrent] = useState("0");

    useEffect(() => {
        const fetchData = async () => {
            const result = await axios(servicePath.getTypeInfo).then(res => {
                return res.data.data;
            })
            setNavArray(result);
        }
        fetchData();
    }, []);

    // 跳转到列表页
    const handleClick = (e) => {
        if (e.key == 0) {
            Router.push('/')
        } else {
            Router.push(`/list?id=${e.key}`)
        }
        setCurrent(e.key);
    }

    // icon图标集合
    const IconMap = {
        home: <HomeOutlined />,
        youtube: <YoutubeOutlined />,
        message: <MessageOutlined />,
        smile: <SmileOutlined />
    };

    const getMenuList = (navList) => {
        return navList.reduce((pre, item) => {
            const { typeName, Id, icon } = item;
            pre.push({
                label: typeName,
                key: Id,
                icon: icon && IconMap[icon]
            });
            return pre;
        }, [])
    }

    const headerMenu = useMemo(() => {
        return getMenuList(navArray);
    }, [navArray]);

    return (
        <div className="header">
            <Row type="flex" justify="center">
                <Col xs={24} sm={24} md={10} lg={13} xl={11}>
                    <span className="header-logo">
                        <Link href={{ pathname: '/' }}>红石榴21</Link>
                    </span>
                    <span className="header-txt">专注前端开发,每年100集免费视频。</span>
                </Col>

                <Col className="memu-div" xs={0} sm={0} md={14} lg={10} xl={7}>
                    <Menu mode="horizontal" selectedKeys={[current]} onClick={handleClick} items={headerMenu}></Menu>
                </Col>
            </Row>
        </div>
    )
}

export default Header;